#!/usr/bin/env coffee

import MDBX from './db/mdbx.coffee'
import '@rmw/console/global'
import sleep from 'await-sleep'
import Nkn from './nkn/init.coffee'
import Seed from './const/seed.coffee'
import {rmw_utf8_encode, rmw_utf8_decode,Ed25519Secret, Ed25519Public} from 'rust'

###
as = "把家里吃不完的饺子皮用来做这个一口一个的青椒火腿土豆饼吧！皮薄馅大，金黄酥脆，真的太好吃了😋明天早餐你也快点试试吧"

a = Buffer.from as,'utf8'
console.log a.length,"a.length"
b = rmw_utf8_encode a
console.log b.length,"b.length"
console.log rmw_utf8_decode(b) == as

seed = Seed()
nkn = await Nkn seed.toString 'hex'
###

###

console.log nkn

sk = Ed25519Secret.load(seed)

buf = Buffer.from('123','utf8')
sign = sk.sign(buf)
console.log sk.verify(buf,sign)

pk = sk.public()
console.log pk.dump()
pk = sk.public()
console.log pk.dump()
pk = sk.public()
console.log pk.dump()
pk = Ed25519Public.load(pk.dump())

console.log pk.verify(buf,sign)
###

#import * as CMD from './const/cmd.coffee'
#import Kad from './lib/kad.coffee'


###
cmd = do =>
  obj = {}
  _send = (cmd)=>
    (addr, args...)=>
      console.log addr, cmd, args
      args.unshift cmd
      nkn.send1 addr, Buffer.concat(args)

  for k,v of CMD
    obj[k.toLowerCase()] = _send Buffer.from [v]

  obj

EMPTY = Buffer.from []

addr_bin = Buffer.from nkn.addr,'hex'
KAD = new Kad(
  0
  addr_bin
  (addr)=>
    console.log "ping >", addr
    try
      nkn.send1 addr, EMPTY
    catch err
      console.error err
      return false
    return true
)

try
  console.log 'subscribe', await nkn.subscribe('12134',400000)
catch err
  console.log err

console.log '!!!>>>', await nkn.getSubscribers('rmw-test')

nkn.onMessage (msg)=>
  {src, identifier, payload} = msg
  {length} = payload
  if not length
    console.log 'ping <', src
    return
  console.log 'msg', msg
  switch payload[0]
    when CMD.FIND
      {length} = payload
      if src.length != 64 # 有identifier 的长度不为64
        return
      console.log KAD

      src = Buffer.from(src,'hex')

      if length == 1
        addr = src
      else if length == 33
        addr = payload[1..]

      setImmediate =>
        KAD.add(src)

      return KAD.get addr
    else
      console.warn 'unknown msg', payload
  return

import DB from './db/sql.coffee'

NKN_KAD = DB.prepare "SELECT addr FROM nkn_kad WHERE site_id=?"

do =>
  console.log nkn.addr

  for {addr} from NKN_KAD.all(0)
    KAD.add addr

  addr = "46fbbb67d4af96ff4c4f2d9d145b18d1220219547c5f96e73523a13c2f82f913"
  try
    await cmd.find addr
  catch err
    return
  console.log KAD.get addr_bin

#console.log same_bit_prefix(a,b)

# 给一个key，查询距离key

#console.log nkn.defaultClient
#console.log nkn.clients
# 创建房间
#   房间名
#   频道公钥
#   订阅者地址
#     nkn
#   房间准入问题
#     问题1
#     问题2
#     问题3
# 房间版本




# 申请加入房间
#

# next
# 分布式网络
#   向距离频道公钥最近的8个地址登记自己的订阅

# 获取xxx的订阅
# 获取xxx的频道
# 获取xxx频道的订阅者
###
